 //
//  GuanZhuListVC.m
//  MPTLive
//
//  Created by HouGeng on 16/1/27.
//  Copyright © 2016年 Jeakin. All rights reserved.
//

#import "GuanZhuListVC.h"
#import "GuanZhuListCell.h"
#import "NSString+MPTString.h"
#import "MPTLoginUser.h"
#import "FootRefreshView.h"
#import "HeadRefreshView.h"
#import "MeInfoMainVC.h"
#import "MPTTips.h"

@interface GuanZhuListVC ()
<UITableViewDataSource,
UITableViewDelegate
>

@property (nonatomic, strong) UITableView *tableV;

@property (nonatomic, strong) NSMutableArray *maryListData;

@property (nonatomic, assign) NSInteger intPage;

/// 取消关注使用
@property (nonatomic, strong) NSIndexPath *indexpath;

@end


@implementation GuanZhuListVC


#pragma mark - ********************** View Lifecycle **********************

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initVariable]; /// 初始化变量
    [self initViews]; /// 初始化界面
    
    /// 发送请求
    if (_fromeType == GuanZhu)
    {
        [self req_URL_follow];
    }
    else
    {
        [self req_URL_fans];
    }
    
    [self regNotification]; /// 注册消息
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[TPTabBarManager share] showBottomView:NO animation:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    // 一定要关注这个函数是否被执行了！！！
}


#pragma mark - ********************** Init All Views **********************

- (void)initVariable
{
    _intPage = 1;
    _maryListData = [NSMutableArray array];
}

- (void)initViews
{
    [self initNavView]; /// 初始化Nav导航栏
    
    /// 根据界面情况，决定是单独写函数，或直接写Views
    [self initMainViews];
}

- (void)initNavView
{
    /// 创建导航栏
    NSString *strTitleName;
    /// 有suid是登录者看别人
    if (ZB_Str_Is_Valid(_suid))
    {
        strTitleName = self.fromeType == FenShi ? @"Ta的粉丝":@"Ta关注的人";
    }
    else
    {
        strTitleName = self.fromeType == FenShi ? @"我的粉丝":@"我关注的人";
    }
    
    [self createNavBarViewWithTitle:strTitleName];
    self.superNavBarView.viewBottomLine.hidden = YES;
    self.superNavBarView.backgroundColor = RGBAColor(254, 222, 9, 1);
    /// 创建左侧按钮
    [self createNavLeftBtnWithItem:@""
                            target:self
                            action:@selector(btnClickBack:)];
    [self.superNavBarView.btnLeft setImage:[UIImage imageNamed:@"CommonBack"] forState:UIControlStateNormal];
}

- (void)initMainViews
{
    _tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, TP_NavBar_H, screenW, screenH - TP_NavBar_H) style:UITableViewStylePlain];
    _tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableV.showsHorizontalScrollIndicator = NO;
    _tableV.showsVerticalScrollIndicator = NO;
    _tableV.delegate = self;
    _tableV.dataSource = self;
    [self.view addSubview:_tableV];
    
    // 下拉刷新和上拉分页
    [_tableV addFootRefreshViewWithTarget:self advanceRefresh:YES action:@selector(fectchMoreData)];
    [_tableV.YX_FootRefreshView addCustomView:[FootRefreshView createFootRefresh]];
    
    [_tableV addHeadRefreshViewWithTarget:self action:@selector(fectchNewData)];
    [_tableV.YX_HeadRefreshView addCustomView:[HeadRefreshView createHeadRefresh]];
}


#pragma mark - ********************** Functions **********************

#pragma mark - 注册消息

- (void)regNotification
{
    
}

/// 关注逻辑
- (void)guanZhuFunction:(NSIndexPath *)indxepath
{
    NSDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:_maryListData[indxepath.row]];
    
    /// 用户关系
    if ([mdic[@"relation"] integerValue] == 3) /// 相互关注变成我没关注
    {
        [self req_GuanZhuWithUserId:ZB_Str_Protect(mdic[@"user"][@"suid"]) relation:[mdic[@"relation"] integerValue] isBool:NO];
        
        /// 改变数据原
        [mdic setValue:@([mdic[@"relation"] integerValue] - 1) forKey:@"relation"];
        [_maryListData replaceObjectAtIndex:indxepath.row withObject:mdic];
        
    }
    else if ([mdic[@"relation"] integerValue] == 2) /// 我没关注变成相互关注
    {
        [self req_GuanZhuWithUserId:ZB_Str_Protect(mdic[@"user"][@"suid"]) relation:[mdic[@"relation"] integerValue] isBool:YES];
        /// 改变数据原
        [mdic setValue:@([mdic[@"relation"] integerValue] + 1) forKey:@"relation"];
        [_maryListData replaceObjectAtIndex:indxepath.row withObject:mdic];
        
    }
    else if ([mdic[@"relation"] integerValue] == 1) /// 我关注了他变成没有
    {
        [self req_GuanZhuWithUserId:ZB_Str_Protect(mdic[@"user"][@"suid"]) relation:[mdic[@"relation"] integerValue] isBool:NO];
        
        /// 改变数据原
        [mdic setValue:@([mdic[@"relation"] integerValue] - 1) forKey:@"relation"];
        [_maryListData replaceObjectAtIndex:indxepath.row withObject:mdic];
    }
    else if ([mdic[@"relation"] integerValue] == 0)
    {
        [self req_GuanZhuWithUserId:ZB_Str_Protect(mdic[@"user"][@"suid"]) relation:[mdic[@"relation"] integerValue] isBool:YES];
        /// 改变数据原
        [mdic setValue:@([mdic[@"relation"] integerValue] + 1) forKey:@"relation"];
        [_maryListData replaceObjectAtIndex:indxepath.row withObject:mdic];
    }
}

- (void)fectchNewData
{
    _intPage = 1;
    
    if (_fromeType == GuanZhu)
    {
        [self req_URL_follow];
    }
    else
    {
        [self req_URL_fans];
    }
    
}

- (void)fectchMoreData
{
    _intPage++;
    if (_fromeType == GuanZhu)
    {
        [self req_URL_follow];
    }
    else
    {
        [self req_URL_fans];
    }
}


#pragma mark - ********************** Button Touch Event **********************

- (void)btnClickBack:(TPButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - ********************** Net Connection Event **********************

#pragma mark - 请求 xxx

- (void)req_URL_follow
{
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSDictionary *paraDic = @{@"os":@"ios",
                              @"page":@(_intPage),
                              @"version":ZB_Str_Protect(version),
                              @"unique_id":ZB_Str_Protect([NSString MPTIdentifierString]),
                              @"suid":ZB_Str_Is_Valid(_suid)?_suid:[MPTLoginUser unArchiver].suid,
                              @"per": @"20",
                               @"area": @"1"};
    
    __weak GuanZhuListVC *Weakself = self;
    [[MPTHttpClient sharedMPHTTPClient] getPath:@"m/v2relation/follow.json" parameters:paraDic queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO  success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            if ([responseObject[@"status"] integerValue] == 200)
            {
                /// 加保护
                if ([responseObject[@"result"] isKindOfClass:[NSArray class]])
                {
                    if (Weakself.intPage == 1)
                    {
                        [Weakself.maryListData removeAllObjects];
                    }
                    [Weakself.maryListData addObjectsFromArray:responseObject[@"result"]];
                }
                
                if (Weakself.maryListData.count <= 0)
                {
                     [MPTTips showSingleTips:@"暂时没有关注信息哦！" duration:1.0f];
                    [Weakself.navigationController popViewControllerAnimated:YES];
                }
            }
            [Weakself.tableV reloadData];
        }
        
        /// 取消刷新状态
        [Weakself.tableV.YX_HeadRefreshView endRefreshing];
        [Weakself.tableV.YX_FootRefreshView noDataRefresh:NO];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        /// 取消刷新状态
        [Weakself.tableV.YX_HeadRefreshView endRefreshing];
        [Weakself.tableV.YX_FootRefreshView noDataRefresh:NO];
        
    } cached:nil];

}

- (void)req_URL_fans
{
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSDictionary *paraDic = @{@"os":@"ios",
                              @"page":@(_intPage),
                              @"version":ZB_Str_Protect(version),
                              @"unique_id":ZB_Str_Protect([NSString MPTIdentifierString]),
                              @"suid":ZB_Str_Is_Valid(_suid)?_suid:[MPTLoginUser unArchiver].suid,
                              @"per": @"20",
                              @"area": @"1"};
    
    __weak GuanZhuListVC *Weakself = self;
    [[MPTHttpClient sharedMPHTTPClient] getPath:@"m/v2relation/fans.json" parameters:paraDic queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO  success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            if ([responseObject[@"status"] integerValue] == 200)
            {
                /// 加保护
                if ([responseObject[@"result"] isKindOfClass:[NSArray class]])
                {
                    if (Weakself.intPage == 1)
                    {
                        [Weakself.maryListData removeAllObjects];
                    }
                    [Weakself.maryListData addObjectsFromArray:responseObject[@"result"]];
                }
                
                if (Weakself.maryListData.count <= 0)
                {
                    [MPTTips showSingleTips:@"暂时没有粉丝信息哦！" duration:1.0f];
                    [Weakself.navigationController popViewControllerAnimated:YES];
                }
            }
            [Weakself.tableV reloadData];
        }
        
        /// 取消刷新状态
        [Weakself.tableV.YX_HeadRefreshView endRefreshing];
        [Weakself.tableV.YX_FootRefreshView noDataRefresh:NO];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        /// 取消刷新状态
        [Weakself.tableV.YX_HeadRefreshView endRefreshing];
        [Weakself.tableV.YX_FootRefreshView noDataRefresh:NO];
        
    } cached:nil];
    
}

/// 关注取消关注
- (void)req_GuanZhuWithUserId:(NSString *)strUserId relation:(NSInteger)relation isBool:(BOOL)isBool
{
    [[MPTHttpClient sharedMPHTTPClient]changeUserRelation:isBool suid:strUserId current:relation success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
    }];

}

#pragma mark - ********************** Delegate Event **********************

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _maryListData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GuanZhuListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GuanZhuListCell"];
    if (!cell)
    {
        cell = [[GuanZhuListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"GuanZhuListCell"];
    }
    
    cell.indexpath = indexPath;
    cell.dic = _maryListData[indexPath.row];
    
    /// 点击了关注等block
    __weak GuanZhuListVC *weakSelf = self;
    [cell setBlock:^(NSIndexPath *indxepath)
    {
        [weakSelf guanZhuFunction:indxepath];
    }];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    /// 跳到个人页面
    MeInfoMainVC *vc = [[MeInfoMainVC alloc] init];
    vc.suid = _maryListData[indexPath.row][@"user"][@"suid"];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - ********************** Notification Event **********************

#pragma mark - 通知 xxx



@end
